﻿using System;
using System.Collections.Generic;

namespace YudiStudio.VSTO.CardClock.Utilities.Conver
{
	public class Json
	{
		public static string LastErrorInfo { get; set; }
		/// <summary>
		/// JSON转对象
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="jsonString"></param>
		/// <returns></returns>
		public static T ToObject<T>(string jsonString)
		{
			try
			{
				return System.Text.Json.JsonSerializer.Deserialize<T>(jsonString, new System.Text.Json.JsonSerializerOptions
				{
					ReadCommentHandling = System.Text.Json.JsonCommentHandling.Skip,
					AllowTrailingCommas = true,
					PropertyNamingPolicy = System.Text.Json.JsonNamingPolicy.CamelCase,
					WriteIndented = true
				});

			}
			catch (Exception ex)
			{
				LastErrorInfo = ex.Message;
				return default;
			}
		}

		/// <summary>
		/// Json转List
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="jsonString"></param>
		/// <returns></returns>
		public static List<T> ToList<T>(string jsonString)
		{
			try
			{
				return System.Text.Json.JsonSerializer.Deserialize<List<T>>(jsonString, new System.Text.Json.JsonSerializerOptions
				{
					ReadCommentHandling = System.Text.Json.JsonCommentHandling.Skip,
					AllowTrailingCommas = true,
					PropertyNamingPolicy = System.Text.Json.JsonNamingPolicy.CamelCase,
					WriteIndented = true
				});
			}
			catch (Exception ex)
			{
				LastErrorInfo = ex.Message;
				return default;
			}
		}
	}
}
